<template>
  <div class="statistics-board" :class="{ 'fullscreen': isFullscreen }">
    <!-- 顶部工具栏 -->
    <div class="toolbar" v-if="!isFullscreen">
      <div class="toolbar-left">
        <h2>运营总览看板</h2>
        <span class="last-update">最后更新: {{ lastUpdateTime }}</span>
      </div>
      <div class="toolbar-right">
        <el-button @click="refreshData" :loading="loading" icon="el-icon-refresh">刷新</el-button>
        <el-button @click="toggleFullscreen" icon="el-icon-full-screen">全屏</el-button>
      </div>
    </div>

    <!-- 全屏模式下的顶部栏 -->
    <div class="fullscreen-header" v-if="isFullscreen">
      <h1>运营总览看板</h1>
      <div class="fullscreen-controls">
        <span class="update-time">{{ lastUpdateTime }}</span>
        <el-button @click="toggleFullscreen" type="text" icon="el-icon-close">退出全屏</el-button>
      </div>
    </div>

    <!-- 核心指标区域 -->
    <div class="metrics-section">
      <h3 class="section-title">核心指标</h3>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" v-for="metric in coreMetrics" :key="metric.key">
          <div class="metric-card">
            <div class="metric-icon">
              <i :class="metric.icon"></i>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ metric.value }}</div>
              <div class="metric-label">{{ metric.label }}</div>
              <div class="metric-growth" :class="metric.growthType">
                <i :class="metric.growthIcon"></i>
                {{ metric.growth }}
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 实时监控区域 -->
    <div class="monitor-section">
      <h3 class="section-title">实时监控</h3>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" v-for="monitor in realtimeMonitors" :key="monitor.key">
          <div class="monitor-card">
            <div class="monitor-header">
              <span class="monitor-title">{{ monitor.title }}</span>
              <div class="monitor-status" :class="monitor.status"></div>
            </div>
            <div class="monitor-value">{{ monitor.value }}</div>
            <div class="monitor-compare">
              <span class="compare-item">
                同比: <span :class="monitor.yoyType">{{ monitor.yoy }}</span>
              </span>
              <span class="compare-item">
                环比: <span :class="monitor.momType">{{ monitor.mom }}</span>
              </span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 异常预警区域 -->
    <div class="alert-section">
      <h3 class="section-title">异常预警</h3>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
          <div class="alert-card">
            <div class="alert-header">
              <i class="el-icon-warning alert-icon"></i>
              <span class="alert-title">低库存商品</span>
              <el-badge :value="(lowStockAlerts || []).length" class="alert-badge" type="danger"></el-badge>
            </div>
            <div class="alert-list">
              <div v-for="item in (lowStockAlerts || []).slice(0, 5)" :key="item.id" class="alert-item">
                <span class="item-name">{{ item.name }}</span>
                <span class="item-value danger">剩余{{ item.stock }}件</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
          <div class="alert-card">
            <div class="alert-header">
              <i class="el-icon-error alert-icon"></i>
              <span class="alert-title">高退款率订单</span>
              <el-badge :value="(highRefundAlerts || []).length" class="alert-badge" type="warning"></el-badge>
            </div>
            <div class="alert-list">
              <div v-for="item in (highRefundAlerts || []).slice(0, 5)" :key="item.id" class="alert-item">
                <span class="item-name">{{ item.name }}</span>
                <span class="item-value warning">{{ item.refundRate }}%</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
          <div class="alert-card">
            <div class="alert-header">
              <i class="el-icon-time alert-icon"></i>
              <span class="alert-title">配送延迟订单</span>
              <el-badge :value="(delayedOrders || []).length" class="alert-badge" type="info"></el-badge>
            </div>
            <div class="alert-list">
              <div v-for="item in (delayedOrders || []).slice(0, 5)" :key="item.id" class="alert-item">
                <span class="item-name">订单{{ item.orderNo }}</span>
                <span class="item-value info">延迟{{ item.delayHours }}小时</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 商品与用户分析区域 -->
    <div class="analysis-section">
      <el-row :gutter="20">
        <!-- 商品分析 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <div class="analysis-card">
            <h3 class="card-title">商品分析</h3>
            <el-tabs v-model="productActiveTab" class="analysis-tabs">
              <el-tab-pane label="热销TOP10" name="hot">
                <div class="chart-container">
                  <div ref="hotProductChart" class="chart"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="滞销TOP10" name="slow">
                <div class="chart-container">
                  <div ref="slowProductChart" class="chart"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="新品表现" name="new">
                <div class="chart-container">
                  <div ref="newProductChart" class="chart"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="分类结构" name="category">
                <div class="chart-container">
                  <div ref="categoryChart" class="chart"></div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>

        <!-- 用户分析 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <div class="analysis-card">
            <h3 class="card-title">用户分析</h3>
            <el-tabs v-model="userActiveTab" class="analysis-tabs">
              <el-tab-pane label="增长曲线" name="growth">
                <div class="chart-container">
                  <div ref="userGrowthChart" class="chart"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="用户分层" name="segment">
                <div class="chart-container">
                  <div ref="userSegmentChart" class="chart"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="RFM模型" name="rfm">
                <div class="chart-container">
                  <div ref="rfmChart" class="chart"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="行为路径" name="behavior">
                <div class="chart-container">
                  <div ref="behaviorChart" class="chart"></div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getCoreMetrics,
  getRealtimeMonitors,
  getAlertData,
  getProductAnalysis,
  getUserAnalysis
} from '@/api/statistics/statisticsBoard'

export default {
  name: 'StatisticsBoard',
  data() {
    return {
      loading: false,
      isFullscreen: false,
      lastUpdateTime: '',
      refreshTimer: null,
      productActiveTab: 'hot',
      userActiveTab: 'growth',

      // 核心指标数据
      coreMetrics: [],

      // 实时监控数据
      realtimeMonitors: [],

      // 预警数据
      lowStockAlerts: [],
      highRefundAlerts: [],
      delayedOrders: [],

      // 商品分析数据
      productAnalysisData: {
        hotProducts: [],
        slowProducts: [],
        newProducts: [],
        categoryStructure: []
      },

      // 用户分析数据
      userAnalysisData: {
        growthData: {
          dates: [],
          newUsers: [],
          activeUsers: []
        },
        userSegment: [],
        rfmModel: [],
        behaviorPath: []
      },

      // 图表实例
      charts: {}
    }
  },

  mounted() {
    this.initData()
    this.startAutoRefresh()
    this.handleFullscreenChange()
  },

  beforeDestroy() {
    this.stopAutoRefresh()
    this.destroyCharts()
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange)
  },

  methods: {
    // 初始化数据
    async initData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadCoreMetrics(),
          this.loadRealtimeMonitors(),
          this.loadAlertData(),
          this.loadProductAnalysis(),
          this.loadUserAnalysis()
        ])
        this.updateLastUpdateTime()
      } catch (error) {
        console.error('数据加载失败:', error)
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },

    // 加载核心指标
    async loadCoreMetrics() {
      const response = await getCoreMetrics()
      this.coreMetrics = response.data
    },

    // 加载实时监控数据
    async loadRealtimeMonitors() {
      const response = await getRealtimeMonitors()
      this.realtimeMonitors = response.data
    },

    // 加载预警数据
    async loadAlertData() {
      const response = await getAlertData()
      this.lowStockAlerts = response.data.lowStock
      this.highRefundAlerts = response.data.highRefund
      this.delayedOrders = response.data.delayed
    },

    // 加载商品分析数据
    async loadProductAnalysis() {
      try {
        const response = await getProductAnalysis()
        this.productAnalysisData = response.data || {
          hotProducts: [],
          slowProducts: [],
          newProducts: [],
          categoryStructure: []
        }
        this.$nextTick(() => {
          this.initProductCharts(this.productAnalysisData)
        })
      } catch (error) {
        console.error('加载商品分析数据失败:', error)
        this.productAnalysisData = {
          hotProducts: [],
          slowProducts: [],
          newProducts: [],
          categoryStructure: []
        }
      }
    },

    // 加载用户分析数据
    async loadUserAnalysis() {
      try {
        const response = await getUserAnalysis()
        this.userAnalysisData = response.data || {
          growthData: {
            dates: [],
            newUsers: [],
            activeUsers: []
          },
          regionData: [],
          behaviorPath: []
        }
        this.$nextTick(() => {
          this.initUserCharts(this.userAnalysisData)
        })
      } catch (error) {
        console.error('加载用户分析数据失败:', error)
        this.userAnalysisData = {
          growthData: {
            dates: [],
            newUsers: [],
            activeUsers: []
          },
          regionData: [],
          behaviorPath: []
        }
      }
    },

    // 初始化商品分析图表
    initProductCharts(data) {
      // 安全检查
      if (!data || typeof data !== 'object') {
        console.warn('商品分析数据为空或格式错误')
        return
      }

      // 等待DOM更新完成
      this.$nextTick(() => {
        // 热销商品图表
        if (this.$refs.hotProductChart && data.hotProducts && Array.isArray(data.hotProducts)) {
          if (this.charts.hotProduct) {
            this.charts.hotProduct.dispose()
          }
          this.charts.hotProduct = echarts.init(this.$refs.hotProductChart)
          this.charts.hotProduct.setOption({
            title: { text: '热销商品TOP10', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(50,50,50,0.7)',
              textStyle: { color: '#fff' }
            },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            xAxis: {
              type: 'category',
              data: data.hotProducts.map(item => item.name || ''),
              axisLabel: {
                rotate: 45,
                color: this.isFullscreen ? '#ccc' : '#666'
              },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } }
            },
            yAxis: {
              type: 'value',
              axisLabel: { color: this.isFullscreen ? '#ccc' : '#666' },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } },
              splitLine: { lineStyle: { color: this.isFullscreen ? '#333' : '#f0f0f0' } }
            },
            series: [{
              type: 'bar',
              data: data.hotProducts.map(item => item.sales || 0),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              },
              barWidth: '60%'
            }]
          })
          this.charts.hotProduct.resize()
        }

        // 滞销商品图表
        if (this.$refs.slowProductChart && data.slowProducts && Array.isArray(data.slowProducts)) {
          if (this.charts.slowProduct) {
            this.charts.slowProduct.dispose()
          }
          this.charts.slowProduct = echarts.init(this.$refs.slowProductChart)
          this.charts.slowProduct.setOption({
            title: { text: '滞销商品TOP10', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(50,50,50,0.7)',
              textStyle: { color: '#fff' }
            },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            xAxis: {
              type: 'category',
              data: data.slowProducts.map(item => item.name || ''),
              axisLabel: {
                rotate: 45,
                color: this.isFullscreen ? '#ccc' : '#666'
              },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } }
            },
            yAxis: {
              type: 'value',
              axisLabel: { color: this.isFullscreen ? '#ccc' : '#666' },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } },
              splitLine: { lineStyle: { color: this.isFullscreen ? '#333' : '#f0f0f0' } }
            },
            series: [{
              type: 'bar',
              data: data.slowProducts.map(item => item.days || 0),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#F56C6C' },
                  { offset: 1, color: '#E6A23C' }
                ])
              },
              barWidth: '60%'
            }]
          })
          this.charts.slowProduct.resize()
        }

        // 新品表现图表
        if (this.$refs.newProductChart && data.newProducts && Array.isArray(data.newProducts)) {
          if (this.charts.newProduct) {
            this.charts.newProduct.dispose()
          }
          this.charts.newProduct = echarts.init(this.$refs.newProductChart)
          this.charts.newProduct.setOption({
            title: { text: '新品销售表现', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(50,50,50,0.7)',
              textStyle: { color: '#fff' }
            },
            legend: {
            data: ['销量', '转化率'],
            top: 30,
            textStyle: { color: this.isFullscreen ? '#ccc' : '#666' }
          },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: data.newProducts.map(item => item.name || ''),
            axisLabel: {
              rotate: 45,
              color: this.isFullscreen ? '#ccc' : '#666'
            },
            axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } }
          },
          yAxis: [
            {
              type: 'value',
              name: '销量',
              axisLabel: { color: this.isFullscreen ? '#ccc' : '#666' },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } },
              splitLine: { lineStyle: { color: this.isFullscreen ? '#333' : '#f0f0f0' } }
            },
            {
              type: 'value',
              name: '转化率(%)',
              axisLabel: {
                formatter: '{value}%',
                color: this.isFullscreen ? '#ccc' : '#666'
              },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } }
            }
          ],
          series: [
            {
              name: '销量',
              type: 'bar',
              data: data.newProducts.map(item => item.sales || 0),
              itemStyle: { color: '#5470c6' }
            },
            {
              name: '转化率',
              type: 'line',
              yAxisIndex: 1,
              data: data.newProducts.map(item => (item.conversionRate || 0) * 100),
              itemStyle: { color: '#91cc75' }
            }
          ]
        })
        this.charts.newProduct.resize()
      }

      // 分类结构图表
      if (this.$refs.categoryChart && data.categoryStructure && Array.isArray(data.categoryStructure)) {
        if (this.charts.category) {
          this.charts.category.dispose()
        }
        this.charts.category = echarts.init(this.$refs.categoryChart)
        this.charts.category.setOption({
          title: { text: '商品分类销售结构', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(50,50,50,0.7)',
            textStyle: { color: '#fff' }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            textStyle: { color: this.isFullscreen ? '#ccc' : '#666' }
          },
          series: [{
            type: 'pie',
            radius: '50%',
            data: data.categoryStructure.map(item => ({
              value: item.sales || 0,
              name: item.category || ''
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        })
        this.charts.category.resize()
      }
      })
    },

    // 初始化用户分析图表
    initUserCharts(data) {
      // 安全检查
      if (!data || typeof data !== 'object') {
        console.warn('用户分析数据为空或格式错误')
        return
      }

      // 等待DOM更新完成
      this.$nextTick(() => {
        // 用户增长图表
        if (this.$refs.userGrowthChart && data.growthData && data.growthData.dates) {
          if (this.charts.userGrowth) {
            this.charts.userGrowth.dispose()
          }
          this.charts.userGrowth = echarts.init(this.$refs.userGrowthChart)
          this.charts.userGrowth.setOption({
            title: { text: '用户增长趋势', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(50,50,50,0.7)',
              textStyle: { color: '#fff' }
            },
            legend: {
              data: ['新增用户', '活跃用户'],
              top: 30,
              textStyle: { color: this.isFullscreen ? '#ccc' : '#666' }
            },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            xAxis: {
              type: 'category',
              data: data.growthData.dates || [],
              axisLabel: { color: this.isFullscreen ? '#ccc' : '#666' },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } }
            },
            yAxis: {
              type: 'value',
              axisLabel: { color: this.isFullscreen ? '#ccc' : '#666' },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } },
              splitLine: { lineStyle: { color: this.isFullscreen ? '#333' : '#f0f0f0' } }
            },
            series: [
              {
                name: '新增用户',
                type: 'line',
                data: data.growthData.newUsers || [],
                smooth: true,
                itemStyle: { color: '#5470c6' }
              },
              {
                name: '活跃用户',
                type: 'line',
                data: data.growthData.activeUsers || [],
                smooth: true,
                itemStyle: { color: '#91cc75' }
              }
            ]
          })
          this.charts.userGrowth.resize()
        }

        // 用户分层图表
        if (this.$refs.userSegmentChart && data.userSegment && Array.isArray(data.userSegment)) {
          if (this.charts.userSegment) {
            this.charts.userSegment.dispose()
          }
          this.charts.userSegment = echarts.init(this.$refs.userSegmentChart)
          this.charts.userSegment.setOption({
            title: { text: '用户分层分布', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
            tooltip: {
              trigger: 'item',
              backgroundColor: 'rgba(50,50,50,0.7)',
              textStyle: { color: '#fff' }
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              textStyle: { color: this.isFullscreen ? '#ccc' : '#666' }
            },
            series: [{
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              data: data.userSegment.map(item => ({
                value: item.count || 0,
                name: item.segment || ''
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }]
          })
          this.charts.userSegment.resize()
        }

        // RFM模型图表
        if (this.$refs.rfmChart && data.rfmModel && Array.isArray(data.rfmModel)) {
          if (this.charts.rfm) {
            this.charts.rfm.dispose()
          }
          this.charts.rfm = echarts.init(this.$refs.rfmChart)
          const option = {
            title: { text: 'RFM用户价值分布', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(50,50,50,0.7)',
              textStyle: { color: '#fff' }
            },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            xAxis: {
              type: 'category',
              data: data.rfmModel.map(item => item.segment || ''),
              axisLabel: {
                rotate: 45,
                color: this.isFullscreen ? '#ccc' : '#666'
              },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } }
            },
            yAxis: {
              type: 'value',
              axisLabel: { color: this.isFullscreen ? '#ccc' : '#666' },
              axisLine: { lineStyle: { color: this.isFullscreen ? '#555' : '#e6e6e6' } },
              splitLine: { lineStyle: { color: this.isFullscreen ? '#333' : '#f0f0f0' } }
            },
            series: [{
              type: 'bar',
              data: data.rfmModel.map(item => item.count || 0),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#E6A23C' },
                  { offset: 1, color: '#F56C6C' }
                ])
              },
              barWidth: '60%'
            }]
          }
          this.charts.rfm.setOption(option)
          this.$nextTick(() => {
            this.charts.rfm.resize()
          })
          }

          // 行为路径图表
          if (this.$refs.behaviorChart && data.behaviorPath && Array.isArray(data.behaviorPath)) {
            if (this.charts.behavior) {
              this.charts.behavior.dispose()
            }
            this.charts.behavior = echarts.init(this.$refs.behaviorChart)
            this.charts.behavior.setOption({
              title: { text: '用户行为转化漏斗', left: 'center', textStyle: { color: this.isFullscreen ? '#fff' : '#333' } },
              tooltip: {
                trigger: 'item',
                backgroundColor: 'rgba(50,50,50,0.7)',
                textStyle: { color: '#fff' }
              },
              series: [{
                type: 'funnel',
                left: '10%',
                top: 60,
                bottom: 60,
                width: '80%',
                min: 0,
                max: 100,
                minSize: '0%',
                maxSize: '100%',
                sort: 'descending',
                gap: 2,
                label: {
                  show: true,
                  position: 'inside',
                  color: '#fff'
                },
                labelLine: {
                  length: 10,
                  lineStyle: {
                    width: 1,
                    type: 'solid'
                  }
                },
                itemStyle: {
                  borderColor: '#fff',
                  borderWidth: 1
                },
                emphasis: {
                  label: {
                    fontSize: 20
                  }
                },
                data: data.behaviorPath.map(item => ({
                  value: item.conversionRate || 0,
                  name: item.step || ''
                }))
              }]
            })
            this.charts.behavior.resize()
          }
        })
      },

    // 刷新数据
    async refreshData() {
      await this.initData()
    },

    // 切换全屏
    toggleFullscreen() {
      if (!this.isFullscreen) {
        this.enterFullscreen()
      } else {
        this.exitFullscreen()
      }
    },

    // 进入全屏
    enterFullscreen() {
      const element = this.$el
      if (element.requestFullscreen) {
        element.requestFullscreen()
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
      }
    },

    // 退出全屏
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
    },

    // 处理全屏状态变化
    handleFullscreenChange() {
      document.addEventListener('fullscreenchange', () => {
        this.isFullscreen = !!document.fullscreenElement
        this.$nextTick(() => {
          this.resizeCharts()
        })
      })
    },

    // 开始自动刷新
    startAutoRefresh() {
      // 每分钟刷新一次
      this.refreshTimer = setInterval(() => {
        if (document.visibilityState === 'visible') {
          this.refreshData()
        }
      }, 60000)
    },

    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },

    // 更新最后更新时间
    updateLastUpdateTime() {
      this.lastUpdateTime = new Date().toLocaleString()
    },

    // 调整图表大小
    resizeCharts() {
      this.$nextTick(() => {
        Object.values(this.charts).forEach(chart => {
          if (chart && chart.resize) {
            chart.resize()
          }
        })
      })
    },

    // 销毁图表
    destroyCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart && chart.dispose) {
          chart.dispose()
        }
      })
      this.charts = {}
    },

    // 更新图表主题
    updateChartsTheme() {
      // 重新初始化所有图表以应用新主题
      this.destroyCharts()
      this.initCharts()
    },

    // 格式化数字
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k'
      }
      return num.toString()
    },

    // 格式化百分比
    formatPercent(num) {
      return (num * 100).toFixed(1) + '%'
    },

    // 获取增长率颜色
    getGrowthColor(rate) {
      return rate >= 0 ? '#67C23A' : '#F56C6C'
    },

    // 获取增长率图标
    getGrowthIcon(rate) {
      return rate >= 0 ? 'el-icon-top' : 'el-icon-bottom'
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-board {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 84px);
  transition: all 0.3s ease;

  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    padding: 20px;
    min-height: 100vh;
    color: #fff;
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);

  .toolbar-left {
    h2 {
      margin: 0 0 5px 0;
      color: #303133;
    }

    .last-update {
      color: #909399;
      font-size: 12px;
    }
  }
}

.fullscreen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: rgba(255,255,255,0.1);
  border-radius: 8px;

  h1 {
    margin: 0;
    color: #fff;
  }

  .fullscreen-controls {
    display: flex;
    align-items: center;
    gap: 15px;

    .update-time {
      color: #ccc;
      font-size: 14px;
    }
  }
}

.section-title {
  margin: 0 0 15px 0;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
  color: #303133;

  .fullscreen & {
    color: #fff;
    border-left-color: #67C23A;
  }
}

.metrics-section {
  margin-bottom: 30px;
}

.metric-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 15px;

  .fullscreen & {
    background: rgba(255,255,255,0.1);
    color: #fff;
  }

  .metric-icon {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #409EFF;
    margin-right: 15px;

    i {
      font-size: 24px;
      color: #fff;
    }
  }

  .metric-content {
    flex: 1;

    .metric-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;

      .fullscreen & {
        color: #fff;
      }
    }

    .metric-label {
      color: #909399;
      font-size: 14px;
      margin-bottom: 5px;

      .fullscreen & {
        color: #ccc;
      }
    }

    .metric-growth {
      font-size: 12px;

      &.positive {
        color: #67C23A;
      }

      &.negative {
        color: #F56C6C;
      }

      &.neutral {
        color: #909399;
      }
    }
  }
}

.monitor-section {
  margin-bottom: 30px;
}

.monitor-card {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 15px;

  .fullscreen & {
    background: rgba(255,255,255,0.1);
    color: #fff;
  }

  .monitor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .monitor-title {
      font-weight: bold;
      color: #303133;

      .fullscreen & {
        color: #fff;
      }
    }

    .monitor-status {
      width: 8px;
      height: 8px;
      border-radius: 50%;

      &.online {
        background: #67C23A;
      }

      &.warning {
        background: #E6A23C;
      }

      &.offline {
        background: #F56C6C;
      }
    }
  }

  .monitor-value {
    font-size: 28px;
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 10px;

    .fullscreen & {
      color: #67C23A;
    }
  }

  .monitor-compare {
    display: flex;
    gap: 15px;

    .compare-item {
      font-size: 12px;
      color: #909399;

      .fullscreen & {
        color: #ccc;
      }

      .positive {
        color: #67C23A;
      }

      .negative {
        color: #F56C6C;
      }
    }
  }
}

.alert-section {
  margin-bottom: 30px;
}

.alert-card {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 15px;

  .fullscreen & {
    background: rgba(255,255,255,0.1);
    color: #fff;
  }

  .alert-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .alert-icon {
      font-size: 18px;
      margin-right: 8px;
      color: #E6A23C;
    }

    .alert-title {
      font-weight: bold;
      color: #303133;
      flex: 1;

      .fullscreen & {
        color: #fff;
      }
    }
  }

  .alert-list {
    .alert-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;

      .fullscreen & {
        border-bottom-color: rgba(255,255,255,0.1);
      }

      &:last-child {
        border-bottom: none;
      }

      .item-name {
        color: #606266;
        font-size: 14px;

        .fullscreen & {
          color: #ccc;
        }
      }

      .item-value {
        font-size: 12px;
        font-weight: bold;

        &.danger {
          color: #F56C6C;
        }

        &.warning {
          color: #E6A23C;
        }

        &.info {
          color: #409EFF;
        }
      }
    }
  }
}

.analysis-section {
  margin-bottom: 30px;
}

.analysis-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 15px;

  .fullscreen & {
    background: rgba(255,255,255,0.1);
    color: #fff;
  }

  .card-title {
    margin: 0;
    padding: 20px 20px 0 20px;
    color: #303133;

    .fullscreen & {
      color: #fff;
    }
  }

  .analysis-tabs {
    padding: 0 20px 20px 20px;

    .chart-container {
      height: 300px;

      .chart {
        width: 100%;
        height: 100%;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .statistics-board {
    padding: 10px;
  }

  .toolbar {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }

  .metric-card {
    flex-direction: column;
    text-align: center;

    .metric-icon {
      margin-right: 0;
      margin-bottom: 10px;
    }
  }

  .analysis-section {
    .analysis-card {
      .chart-container {
        height: 250px;
      }
    }
  }
}
</style>
